import React, { Component } from 'react';
import { connect } from 'dva';
import { Card, Table, Divider, Button, Popconfirm } from 'antd';
import { deleteLine } from 'Services/publicServer.js';

const STORE_NAME = 'lineManagement';

@connect(state => ({
  [STORE_NAME]: state[STORE_NAME],
  loading: state.loading.effects[`${STORE_NAME}/fetchTableDataSource`],
}))
class lineManagement extends Component {
  constructor(props) {
    super(props);
    window.scope = this;
  }

  componentDidMount() {
    this.fetchData();
  }

  getDataFromStore = key => (key ? this.props[STORE_NAME][key] : this.props[STORE_NAME]);

  fetchData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: `${STORE_NAME}/fetchTableDataSource`,
    });
  };

  delectItem = id => {
    deleteLine({ id }).then(this.fetchData);
  };

  handlePaginationChange = (pageNo, pageSize) => {
    const { dispatch } = this.props;
    dispatch({
      type: `${STORE_NAME}/updatePagination`,
      payload: { pageNo, pageSize },
    });
  };

  columns = [
    {
      title: '线路名',
      key: 'lineName',
      dataIndex: 'lineName',
    },
    {
      title: '描述',
      key: 'describe',
      dataIndex: 'describe',
    },
    {
      title: '始发车',
      key: 'startbus',
      dataIndex: 'startbus',
    },
    {
      title: '晚班车',
      key: 'endbus',
      dataIndex: 'endbus',
    },
    {
      title: '操作',
      key: 'gener',
      render: (_, { id }) => (
        <span>
          <a
            onClick={() => {
              this.props.history.push(`/lineManagement/lineDetail/edit/?id=${id}`);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <Popconfirm title="你确定要删除吗？" onConfirm={this.delectItem.bind(this, id)}>
            <a>删除</a>
          </Popconfirm>
        </span>
      ),
    },
  ];

  pagination = () => ({
    current: +this.getDataFromStore('pageNo'),
    pageSize: +this.getDataFromStore('pageSize'),
    total: +this.getDataFromStore('total'),
    showQuickJumper: true,
    showSizeChanger: true,
    onChange: this.handlePaginationChange,
    onShowSizeChange: this.handlePaginationChange,
  });

  render() {
    const { columns, pagination } = this;
    const { tableDataSource: dataSource } = this.getDataFromStore();

    return (
      <div>
        <Card
          title="线路管理"
          extra={
            <Button
              type="primary"
              onClick={() => {
                this.props.history.push(`/lineManagement/lineDetail/add/`);
              }}
            >
              添加线路
            </Button>
          }
        >
          <Table
            bordered
            loading={this.props.loading}
            columns={columns}
            dataSource={dataSource}
            pagination={pagination()}
          />
        </Card>
      </div>
    );
  }
}

export default lineManagement;
